<script setup>
import { h, onMounted, ref,computed, resolveDirective, withDirectives } from 'vue'
import {
  NButton,
  NCheckbox,
  NCheckboxGroup,
  NForm,
  NFormItem,
  NImage,
  NInput,
  NSpace,
  NSwitch,
  NTag,
  NPopconfirm,
  NLayout,
  NLayoutSider,
  NLayoutContent,
  NTreeSelect,
  useMessage,
  NFlex,
  NAvatar, NSelect, NInputNumber
} from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import QueryBarItem from '@/components/query-bar/QueryBarItem.vue'
import CrudModal from '@/components/table/CrudModal.vue'
import CrudTable from '@/components/table/CrudTable.vue'
import { getToken } from '@/utils'
import { formatDate, renderIcon } from '@/utils'
import { useCRUD } from '@/composables'
// import { loginTypeMap, loginTypeOptions } from '@/constant/data'
import api from '@/api'
import TheIcon from '@/components/icon/TheIcon.vue'
import { useUserStore } from '@/store'

const message = useMessage()
defineOptions({ name: '排班' })
const {
  modalVisible,
  modalTitle,
  modalAction,
  modalLoading,
  handleSave,
  modalForm,
  modalFormRef,
  handleEdit,
  handleDelete,
  handleAdd,
} = useCRUD({
  name: '班次管理',
  initForm: {},
  doCreate: api.createSchedulingRules,
  doUpdate: api.updateSchedulingRules,
  doDelete: api.deleteSchedulingRules,
  refresh: () => api.getSchedulingRules().then((res) => (data.banci = res.data)),
})

const data = reactive({
  value: 0,
  banci:[],
  dates:[],
  designers:[],
  week:0,
  space_id:1,
  option_space:[],
  select_date:0
});

onMounted(() => {
  api.getSpaceList().then((res) => {
    data.option_space = res.data
    data.space_id = res.data[0].value
    handlerefresh()
  })

})

function handlerefresh(){
  api.getSchedulingRules().then((res) => (data.banci = res.data))
  api.getSchedulingDatesWeek().then((res) => (data.dates = res.data))
  api.getAllDesigners({space_id:data.space_id}).then((res) => (data.designers = res.data))
}

// 计算选中的颜色
const selectedColor = computed(() => {
  return (date) => {
    const selectedOption = data.banci.find(item => item.value === date.selected);
    return selectedOption ? selectedOption.color : '#ccc'; // 默认颜色
  };
});

// 计算选中的标签
const selectedLabel = computed(() => {
  return (date) => {
    const selectedOption = data.banci.find(item => item.value === date.selected);
    return selectedOption ? selectedOption.label : '弹出选择'; // 默认标签
  };
});



// 当前选择的日期范围（以周为单位）
const timestamp = ref(null);

const onDateChange = (newDate) => {
  console.log(newDate);
  if (!newDate) return;
  data.select_date = newDate

  api.getSchedulingDatesWeek({
    week:newDate
  }).then((res) => (data.dates = res.data))
  api.getAllDesigners({
    week: data.select_date,
    space_id:data.space_id
  }).then((res) => (data.designers = res.data))


};

function onSpaceChange(){
  message.success("切换门店")
  api.getAllDesigners({
    week: data.select_date,
    space_id:data.space_id
  }).then((res) => (data.designers = res.data))
}

const save_sd = (value,item,item2) => {
  // 如果需要保存到后端或其他逻辑，可以在这里实现
  api.createSchedulingDates({
    rules_id:value,
    designer_id:item.id,
    date:item2.date,
    start:"00:00",
    end:"00:00",
    space_id:data.space_id
  }).then((res) => (message.success(item.name+"修改成功")))
};
</script>

<template>
  <AppPage :show-footer="false">

    <n-card title="排班表" :bordered="false" style="height: 100%;">
      <n-card embedded >
        <n-flex justify="space-between">
          <div>
            班次说明:&nbsp;&nbsp;
            <n-button  @click="handleEdit(item)" tertiary style="margin-right: 10px;color:#fff;border:0" :style="'background:'+item.color" v-for="item in data.banci">
              {{item.label}}{{item.desc}}
            </n-button>
            <n-button type="primary"  @click="handleAdd"  >添加班次</n-button>
          </div>
          <div style="display: flex">
            <NSelect
                style="width: 100%;margin-bottom:10px;"
                :options="data.option_space"
                clearable
                placeholder="请选择门店"
                v-model:value="data.space_id"
                @update:value="onSpaceChange"
            />&nbsp;
            <n-date-picker v-model:value="timestamp" type="week" clearable @update:value="onDateChange"/>
          </div>
        </n-flex>
      </n-card>

      <n-card embedded style="margin-top: 10px">
        <n-scrollbar x-scrollable style="width: 100%;height: calc(100vh - 330px);" trigger="none">

          <n-flex class="tb_row" style="background: #9852b4;color:#fff">
            <div class="tb_head">姓名/排班日期</div>
            <div class="tb_head" v-for="item in data.dates">{{item.date}}</div>
          </n-flex>
          <n-flex class="tb_row" v-for="item in data.designers" >
            <div class="tb_head" > <n-button size="large" tertiary class="botton_bg" style="background: #9852b4;color:#fff" >{{item.name}}</n-button></div>
            <div class="tb_head" v-for="(item2,index) in item.dates">
              <n-popselect :key="index" @update:value="(value) => save_sd(value, item,item2)" v-model:value="item.dates[index].selected" :options="data.banci" trigger="click">
                <n-button size="large" tertiary style="color:#fff;border:0;width:100%;" :style="'background:'+selectedColor(item2)">{{ selectedLabel(item2) || '选择' }}</n-button>
              </n-popselect>
            </div>
          </n-flex>
        </n-scrollbar>

      </n-card>
    </n-card>


    <CrudModal v-model:visible="modalVisible" title="班次编辑" :loading="modalLoading" @save="handleSave"
               style="width: 350px !important;"
    >
      <NForm ref="modalFormRef" label-placement="left" label-align="left" :label-width="80"
             :model="modalForm" :rules="validateAddUser"  >

        <NFormItem label="名称" path="label" style="width: 100%;">
          <NInput v-model:value="modalForm.label" clearable placeholder="请输入标题" />
        </NFormItem>

        <NFormItem label="颜色" path="color" style="width: 100%;">
          <n-color-picker v-model:value="modalForm.color" :modes="['hex']" :show-alpha="false" />
        </NFormItem>

        <NFormItem label="开始时间" path="start_time">
          <n-time-picker
              v-model:formatted-value="modalForm.start"
              value-format="HH:mm"
              placeholder="选择开始时间"
              clearable
          />
        </NFormItem>
        <NFormItem label="截止时间" path="end_time">
          <n-time-picker
              v-model:formatted-value="modalForm.end"
              value-format="HH:mm"
              placeholder="选择结束时间"
              clearable
          />
        </NFormItem>




      </NForm>
    </CrudModal>

  </AppPage>
</template>

<style scoped>

.tb_row{

  gap:0px !important;
  width: 2200px;
  border:1px solid #eee;
  height: 50px;
}
.tb_head{
  width:120px;
  text-align: center;
  border-right:1px solid #eee;
  display: flex;
  align-items: center;
  justify-content: center;
}
.botton_bg{
  color:#fff;
  border:0;
  width:100%;
}
</style>